<?php
class Bizprofile_EnterpriseController extends Zend_Controller_Action {

	public function denyAction(){
        $request = $this->getRequest();
		$data    = 
        $enterprise_id = $request->getParam('enterprise_id');
        $user_id = 0;

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $enterpriseDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);
        $enterprise = $enterpriseDao->getById($enterprise_id);
		$this->view->enterprise = $enterprise;
		$this->view->params     = $request->getParams();		
	}
	public function savemapAction(){
		$request = $this->getRequest();
		$params  = $request->getParams();		
		$mapStatic = 'http://maps.google.com/maps/api/staticmap?';
		$enterprise_id = $params["enterprise_id"];
		$center = $params["center"];
		$size   = "300x264";//$params['size'];
		$zoom 	= $params["zoom"];
		$marker = $params["markers"];
		$sensor = $params["sensor"];
		$urlGoogleMapStatic = $mapStatic . "center=".$center .'&zoom='. $zoom .'&size='. $size .'&markers='. $marker. '&sensor='.$sensor;
		$outpath = 'images/maps/'.$enterprise_id.'.png';		
		$gmap = new SplFileObject($outpath,'w');
		$image = file_get_contents($urlGoogleMapStatic);
		$gmap->fwrite($image);		
		die;
	}
	
    public function indexAction() {
        $request = $this->getRequest();
        $enterprise_id = $request->getParam('enterprise_id');
        $user_id = 0;

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $enterpriseDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);
        $enterprise = $enterpriseDao->getById($enterprise_id);
		
        if($enterprise != null){
            $this->view->assign('enterprise', $enterprise);
            $auth = Zend_Auth::getInstance();
            if ($auth->hasIdentity()) {
                $user = $auth->getIdentity();
                $user_id = $user->user_id;
            }
			// Update count_view
			
            $viewCount = $enterpriseDao->getMarketData($enterprise_id);
            $data = new Enterprise_Models_Enterprise(array(
                    'enterprise_id' => $enterprise_id,
                    'view_count'    => 1
            ));
            if(!$viewCount){
                /**Insert new row*/
                $enterpriseDao->addMarketData($data);
            }else{
                /**Update row*/
                $enterpriseDao->updateMarketData($data);
            }
        }

        $permissionDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getPermissionDao();
        $permissionDao->setDbConnection($conn);
        $user_entity = $permissionDao->getUserEntity($user_id,$enterprise_id);
        $this->view->assign('user_entity', $user_entity);

        $permission = $permissionDao->getPermissionByUserEntity($enterprise_id,$user_entity);
        $this->view->assign('permission', $permission);
    }

    public function listAction() {
        $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/enterprise";

        /**Image 1*/
        $file1 = $serUrl."/enterprise_ad1.jpg";
        $path1 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file1);
        $urlImage1 = is_file($path1)?$file1:null;

        /**Image 2*/
        $file2 = $serUrl."/enterprise_ad2.jpg";
        $path2 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file2);
        $urlImage2 = is_file($path2)?$file2:null;

        /**Image 3*/
        $file3 = $serUrl."/enterprise_ad3.jpg";
        $path3 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file3);
        $urlImage3 = is_file($path3)?$file3:null;

        /**Image 4*/
        $file4 = $serUrl."/enterprise_ad4.jpg";
        $path4 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file4);
        $urlImage4 = is_file($path4)?$file4:null;

        /**Image 5*/
        $file5 = $serUrl."/enterprise_ad5.jpg";
        $path5 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file5);
        $urlImage5 = is_file($path5)?$file5:null;

        $arrImage = array(
            1 => $urlImage1,
            2 => $urlImage2,
            3 => $urlImage3,
            4 => $urlImage4,
            5 => $urlImage5,
        );
        $this->view->assign('arrImage', $arrImage);

        /**
         * Get link advertise
        **/
        $file = $serUrl."/link.txt";
        $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
        $arrLink = null;
        if(is_file($path)){
            $content = file_get_contents($path);
            $arrLink = Zend_Json::decode($content);
        }
        $this->view->assign('arrLink', $arrLink);
    }
	
	/*
		Name: Cong Ngo, Date: 1:34 27/04/2011
		Purpose: Thêm action 
			1. testenterprise 		: list all enterprise (active+deactive frontend)
			2. updateactivefrontend : update active frontend with enterprise_id (ajax)
			3. updatedeleted 		: update deleted ->0->1,1->0
		
	*/
    /*
    *****************************       BEGIN  TEST ACTION                   *********************************
    **********************************************************************************************************
    */
	public function testenterprisepagerAction(){
		$this->_helper->getHelper('layout')->disableLayout();
		$request = $this->getRequest();
		$data    = $request->getParams();
		$type    = $data['type'];
		$pageIndex = $data['pageIndex'];
		$this->view->assign('type',$type);	
		$this->view->assign('pageIndex',$pageIndex);	
	}
    /**
     * Format date to strtotime function use
     * @return string
     */	
	public function updatedeletedAction(){
		$request = $this->getRequest();
		$data    = $request->getParams();
		$enterpriseId = $data["id"];
		$msg = null;
		try{
			if(!$enterpriseId)
				throw new Exception("Enterprise Id is empty.");
		   /**
			* Get connection to database
			**/
			$conn = Tomato_Db_Connection::factory()->getMasterConnection();

			/**
			 * Enterprise model access ta data
			 **/
			$enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
			$enterpriseDao->setDbConnection($conn);			
			$enterprise    = $enterpriseDao->getById($enterpriseId,null);
			$enterprise->deleted = ($enterprise->deleted >=1)?0:1;
			$enterpriseDao->update($enterprise);
		}catch(Exception $ex){
			$msg = array("success"=>false,"msg"=>$ex->getMessage());
		}
		if($msg==null)
			$msg = array("success"=>true,"msg"=>"Update enterprise deleted successfull.");
		echo Zend_Json::encode($msg); die();
	}
	public function updateactivefrontendAction(){
		$request = $this->getRequest();
		$data    = $request->getParams();
		$enterpriseId = $data["id"];
		$msg = null;
		try{
			if(!$enterpriseId)
				throw new Exception("Enterprise Id is empty.");
		   /**
			* Get connection to database
			**/
			$conn = Tomato_Db_Connection::factory()->getMasterConnection();

			/**
			 * Enterprise model access ta data
			 **/
			$enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
			$enterpriseDao->setDbConnection($conn);			
			$enterprise    = $enterpriseDao->getById($enterpriseId);
			$enterprise->frontend_active = ($enterprise->frontend_active>=1)?0:1;
			$enterpriseDao->update($enterprise);
		}catch(Exception $ex){
			$msg = array("success"=>false,"msg"=>$ex->getMessage());
		}
		if($msg==null)
			$msg = array("success"=>true,"msg"=>"Update enterprise active successfull.");
		echo Zend_Json::encode($msg); die();
	}
	public function testenterpriseAction(){		
        $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/enterprise";

        /**Image 1*/
        $file1 = $serUrl."/enterprise_ad1.jpg";
        $path1 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file1);
        $urlImage1 = is_file($path1)?$file1:null;

        /**Image 2*/
        $file2 = $serUrl."/enterprise_ad2.jpg";
        $path2 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file2);
        $urlImage2 = is_file($path2)?$file2:null;

        /**Image 3*/
        $file3 = $serUrl."/enterprise_ad3.jpg";
        $path3 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file3);
        $urlImage3 = is_file($path3)?$file3:null;

        /**Image 4*/
        $file4 = $serUrl."/enterprise_ad4.jpg";
        $path4 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file4);
        $urlImage4 = is_file($path4)?$file4:null;

        /**Image 5*/
        $file5 = $serUrl."/enterprise_ad5.jpg";
        $path5 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file5);
        $urlImage5 = is_file($path5)?$file5:null;

        $arrImage = array(
            1 => $urlImage1,
            2 => $urlImage2,
            3 => $urlImage3,
            4 => $urlImage4,
            5 => $urlImage5,
        );
        $this->view->assign('arrImage', $arrImage);

        /**
         * Get link advertise
        **/
        $file = $serUrl."/link.txt";
        $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
        $arrLink = null;
        if(is_file($path)){
            $content = file_get_contents($path);
            $arrLink = Zend_Json::decode($content);
        }
        $this->view->assign('arrLink', $arrLink);
	}
   /*
   *****************************       END TEST ACTION                   ************************************
   **********************************************************************************************************
   */
   public function searchAction(){
        $request = $this->getRequest();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        $exp = array(
            'deleted' => 0,
			'frontend_active'=>1	
        );		
        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $exp['keyword'] = $keyword;
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));

            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'bizprofile_enterprise_search').'/?q='.$params);

        } else {
            $params = $request->getParam('q');
            if (null != $params) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }
        $key = false;
        if(trim($exp['keyword']) != null){
            $key = true;
            $this->view->assign('exp', $exp);
        }
        $this->view->assign('key', $key);
		
        $numBasic = $enterpriseDao->basiccount($exp);
        $numInfo  = $enterpriseDao->infocount($exp);
        $numBlog  = $enterpriseDao->blogcount($exp);
        $this->view->assign('numBasic',$numBasic);
        $this->view->assign('numInfo',$numInfo);
        $this->view->assign('numBlog',$numBlog);
    }

    public function basicAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Info models of enterprise access to data
        **/
        $infoDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
        $infoDao->setDbConnection($conn);
        $infoDao->setLang($lang);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 10;
        $offset     = ($pageIndex - 1) * $perPage;
        $params = null;
        $exp = array(
            'deleted' => 0,
			'frontend_active'=>1
        );

        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $address = $request->getPost('address');
            $city = $request->getPost('city');
            $professions = $request->getPost('professions');
            $type = ($request->getPost('type'))?$request->getPost('type'):'basic';

            $exp['type']    = $type;
            $exp['keyword'] = $keyword;
            $key = true;
            if(trim($exp['keyword']) == null){
                $key = false;
                $this->view->assign('key', $key);
                return;
            }
            $this->view->assign('key', $key);

            if(trim($address) != ''){
                $exp['contact_address'] = $address;
            }
            if($city != 'all'){
                $exp['registration_city'] = $city;
            }
            if($professions != 'all'){
                $exp['professions_id'] = $professions;
            }
			//print_r($exp);
            $enterprises = $enterpriseDao->basic($offset, $perPage, $exp, $type);
            $total       = $enterpriseDao->basiccount($exp, $type);
			//var_dump($total); die;
            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($enterprises, $total));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('enterprises', $enterprises);
            $this->view->assign('numEnterprise', $total);
            $this->view->assign('exp', $exp);
            $this->view->assign('paginator', $paginator);

            $this->view->assign('paginatorOptions', array(
                'path'        => $this->view->url(array(), 'bizprofile_enterprise_basic_ajax'),
                'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
            ));

            /**
            * Get about us follow enterprise
            **/
            $arrInfos = array();
            foreach($enterprises as $enterprise){
                $infos = $infoDao->getInfos($enterprise->id, 5);
                $arrInfos[$enterprise->id] = isset($infos[0])?$infos[0]:null;
            }
            $this->view->assign('arrInfos', $arrInfos);
        }
    }

    public function infoAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 10;
        $offset     = ($pageIndex - 1) * $perPage;
        $params = null;
        $exp = array(
            'deleted' => 0,
        );

        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $exp['keyword'] = $keyword;
            $key = true;
            if(trim($exp['keyword']) == null){
                $key = false;
                $this->view->assign('key', $key);
                return;
            }
            $this->view->assign('key', $key);

            $type = ($request->getPost('type'))?$request->getPost('type'):'basic';
            $exp['type']    = $type;

            $enterprises = $enterpriseDao->info($offset, $perPage, $exp, $type);
            $total       = $enterpriseDao->infocount($exp, $type);

            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($enterprises, $total));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('enterprises', $enterprises);
            $this->view->assign('numEnterprise', $total);
            $this->view->assign('exp', $exp);
            $this->view->assign('paginator', $paginator);

            $this->view->assign('paginatorOptions', array(
                'path'        => $this->view->url(array(), 'bizprofile_enterprise_info_ajax'),
                'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
            ));
        }
    }

    public function blogAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 10;
        $offset     = ($pageIndex - 1) * $perPage;
        $params = null;
        $exp = array(
            'deleted' => 0,
        );

        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $from_date = $request->getPost('from_date');
            $to_date = $request->getPost('to_date');

            $exp['keyword'] = $keyword;
            $key = true;
            if(trim($exp['keyword']) == null){
                $key = false;
                $this->view->assign('key', $key);
                return;
            }
            $this->view->assign('key', $key);
            if($from_date){
                $exp['from_date']   = date('Y-m-d',strtotime($this->convertDateFormat($from_date)));
                $exp['v_from_date'] = $from_date;
            }
            if($to_date){
                $exp['to_date']   = date('Y-m-d',strtotime($this->convertDateFormat($to_date)));
                $exp['v_to_date'] = $to_date;
            }
            $type = ($request->getPost('type'))?$request->getPost('type'):'basic';
            $exp['type']    = $type;

            $enterprises = $enterpriseDao->blog($offset, $perPage, $exp, $type);
            $total       = $enterpriseDao->blogcount($exp, $type);

            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($enterprises, $total));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('enterprises', $enterprises);
            $this->view->assign('numEnterprise', $total);
            $this->view->assign('exp', $exp);
            $this->view->assign('paginator', $paginator);

            $this->view->assign('paginatorOptions', array(
                'path'        => $this->view->url(array(), 'bizprofile_enterprise_blog_ajax'),
                'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
            ));
        }
    }

    public function searchAdvancedAction(){
        $request = $this->getRequest();
        $lang = $request->getParam('lang');
        $this->view->assign('lang', $lang);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Info models of enterprise access to data
        **/
        $infoDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
        $infoDao->setDbConnection($conn);
        $infoDao->setLang($lang);

        /**
         * Get professions for select box
        **/
        $professions = $enterpriseDao->getProfessions();
        $this->view->assign('professions', $professions);

        /**
         * City
        **/
        $arrCity = array(
            'HCM' => 'Hồ Chí Minh',
            'HPG'  => 'Hải Phòng',
            'HNO'  => 'Hà Nội',
            'DNG'  => 'Đà Nẵng',
            'CTH'  => 'Cần Thơ',
            'VTB'  => 'Vũng Tàu',
            'DNA'  => 'Đồng Nai'
        );
        $this->view->assign('city', $arrCity);
    }
    public function convertDateFormat($time){
        $a = explode("/", $time);
        $ts = @$a[2].'/'.@$a[1].'/'.@$a[0];
        return $ts;
    }
}